{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "736b5088280a06f5",
   "metadata": {},
   "source": [
    "# Few-shot prompt templates\n",
    "> In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.<br>\n",
    "> 在本教程中，我们将学习如何创建使用少量示例的提示模板。可以从一组示例或示例选择器对象构造几个样本提示模板。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa347b80e7ca2648",
   "metadata": {},
   "source": [
    "## Using an example set"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f895b2ed3baf2b72",
   "metadata": {},
   "source": [
    "### Create the example set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "21a60ed71f66876",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T10:14:34.637849Z",
     "start_time": "2024-07-17T10:14:34.114203Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain_core.prompts.few_shot import FewShotPromptTemplate\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "\n",
    "examples = [\n",
    "    {\n",
    "        \"question\": \"Who lived longer, Muhammad Ali or Alan Turing?\",\n",
    "        \"answer\": \"\"\"\n",
    "Are follow up questions needed here: Yes.\n",
    "Follow up: How old was Muhammad Ali when he died?\n",
    "Intermediate answer: Muhammad Ali was 74 years old when he died.\n",
    "Follow up: How old was Alan Turing when he died?\n",
    "Intermediate answer: Alan Turing was 41 years old when he died.\n",
    "So the final answer is: Muhammad Ali\n",
    "\"\"\",\n",
    "    },\n",
    "    {\n",
    "        \"question\": \"When was the founder of craigslist born?\",\n",
    "        \"answer\": \"\"\"\n",
    "Are follow up questions needed here: Yes.\n",
    "Follow up: Who was the founder of craigslist?\n",
    "Intermediate answer: Craigslist was founded by Craig Newmark.\n",
    "Follow up: When was Craig Newmark born?\n",
    "Intermediate answer: Craig Newmark was born on December 6, 1952.\n",
    "So the final answer is: December 6, 1952\n",
    "\"\"\",\n",
    "    },\n",
    "    {\n",
    "        \"question\": \"Who was the maternal grandfather of George Washington?\",\n",
    "        \"answer\": \"\"\"\n",
    "Are follow up questions needed here: Yes.\n",
    "Follow up: Who was the mother of George Washington?\n",
    "Intermediate answer: The mother of George Washington was Mary Ball Washington.\n",
    "Follow up: Who was the father of Mary Ball Washington?\n",
    "Intermediate answer: The father of Mary Ball Washington was Joseph Ball.\n",
    "So the final answer is: Joseph Ball\n",
    "\"\"\",\n",
    "    },\n",
    "    {\n",
    "        \"question\": \"Are both the directors of Jaws and Casino Royale from the same country?\",\n",
    "        \"answer\": \"\"\"\n",
    "Are follow up questions needed here: Yes.\n",
    "Follow up: Who is the director of Jaws?\n",
    "Intermediate Answer: The director of Jaws is Steven Spielberg.\n",
    "Follow up: Where is Steven Spielberg from?\n",
    "Intermediate Answer: The United States.\n",
    "Follow up: Who is the director of Casino Royale?\n",
    "Intermediate Answer: The director of Casino Royale is Martin Campbell.\n",
    "Follow up: Where is Martin Campbell from?\n",
    "Intermediate Answer: New Zealand.\n",
    "So the final answer is: No\n",
    "\"\"\",\n",
    "    },\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28825191f6702f44",
   "metadata": {},
   "source": [
    "### Create a formatter for the few-shot examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6bdc938df9633d62",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T10:16:16.061537Z",
     "start_time": "2024-07-17T10:16:16.056464Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Question: Who lived longer, Muhammad Ali or Alan Turing?\n",
      "\n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: How old was Muhammad Ali when he died?\n",
      "Intermediate answer: Muhammad Ali was 74 years old when he died.\n",
      "Follow up: How old was Alan Turing when he died?\n",
      "Intermediate answer: Alan Turing was 41 years old when he died.\n",
      "So the final answer is: Muhammad Ali\n",
      "\n"
     ]
    }
   ],
   "source": [
    "example_prompt = PromptTemplate.from_template(\"Question: {question}\\n{answer}\")\n",
    "\n",
    "print(example_prompt.format(**examples[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2298901741d88b69",
   "metadata": {},
   "source": [
    "### Feed examples and formatter to FewShotPromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "97d12349d9dddfa1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T10:20:17.070477Z",
     "start_time": "2024-07-17T10:20:17.065101Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Question: Who lived longer, Muhammad Ali or Alan Turing?\n",
      "\n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: How old was Muhammad Ali when he died?\n",
      "Intermediate answer: Muhammad Ali was 74 years old when he died.\n",
      "Follow up: How old was Alan Turing when he died?\n",
      "Intermediate answer: Alan Turing was 41 years old when he died.\n",
      "So the final answer is: Muhammad Ali\n",
      "\n",
      "\n",
      "Question: When was the founder of craigslist born?\n",
      "\n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: Who was the founder of craigslist?\n",
      "Intermediate answer: Craigslist was founded by Craig Newmark.\n",
      "Follow up: When was Craig Newmark born?\n",
      "Intermediate answer: Craig Newmark was born on December 6, 1952.\n",
      "So the final answer is: December 6, 1952\n",
      "\n",
      "\n",
      "Question: Who was the maternal grandfather of George Washington?\n",
      "\n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: Who was the mother of George Washington?\n",
      "Intermediate answer: The mother of George Washington was Mary Ball Washington.\n",
      "Follow up: Who was the father of Mary Ball Washington?\n",
      "Intermediate answer: The father of Mary Ball Washington was Joseph Ball.\n",
      "So the final answer is: Joseph Ball\n",
      "\n",
      "\n",
      "Question: Are both the directors of Jaws and Casino Royale from the same country?\n",
      "\n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: Who is the director of Jaws?\n",
      "Intermediate Answer: The director of Jaws is Steven Spielberg.\n",
      "Follow up: Where is Steven Spielberg from?\n",
      "Intermediate Answer: The United States.\n",
      "Follow up: Who is the director of Casino Royale?\n",
      "Intermediate Answer: The director of Casino Royale is Martin Campbell.\n",
      "Follow up: Where is Martin Campbell from?\n",
      "Intermediate Answer: New Zealand.\n",
      "So the final answer is: No\n",
      "\n",
      "\n",
      "Question: Who was the father of Mary Ball Washington?\n"
     ]
    }
   ],
   "source": [
    "prompt = FewShotPromptTemplate(\n",
    "    examples=examples,\n",
    "    example_prompt=example_prompt,\n",
    "    suffix=\"Question: {input}\",\n",
    "    input_variables=[\"input\"],\n",
    ")\n",
    "\n",
    "print(prompt.format(input=\"Who was the father of Mary Ball Washington?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36a6bb9aa4a6da84",
   "metadata": {},
   "source": [
    "## Using an example selector"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dbfd85de706a987f",
   "metadata": {},
   "source": [
    "### Feed examples into ExampleSelector\n",
    "> In this tutorial, we will use the SemanticSimilarityExampleSelector class. This class selects few-shot examples based on their similarity to the input. It uses an embedding model to compute the similarity between the input and the few-shot examples, as well as a vector store to perform the nearest neighbor search.<br>\n",
    "> 在本教程中，我们将使用该 SemanticSimilarityExampleSelector 类。此类根据与输入的相似性选择小样本。它使用嵌入模型来计算输入和少样本示例之间的相似性，并使用向量存储来执行最近邻搜索。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "54be217af6bf4b48",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T10:35:16.513720Z",
     "start_time": "2024-07-17T10:35:02.096787Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Examples most similar to the input: Who was the father of Mary Ball Washington?\n",
      "\n",
      "\n",
      "answer: \n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: Who was the mother of George Washington?\n",
      "Intermediate answer: The mother of George Washington was Mary Ball Washington.\n",
      "Follow up: Who was the father of Mary Ball Washington?\n",
      "Intermediate answer: The father of Mary Ball Washington was Joseph Ball.\n",
      "So the final answer is: Joseph Ball\n",
      "\n",
      "question: Who was the maternal grandfather of George Washington?\n"
     ]
    }
   ],
   "source": [
    "from langchain_chroma import Chroma\n",
    "from langchain_core.example_selectors import SemanticSimilarityExampleSelector\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "example_selector = SemanticSimilarityExampleSelector.from_examples(\n",
    "    # This is the list of examples available to select from.\n",
    "    examples,\n",
    "    # This is the embedding class used to produce embeddings which are used to measure semantic similarity.\n",
    "    OpenAIEmbeddings(),\n",
    "    # This is the VectorStore class that is used to store the embeddings and do a similarity search over.\n",
    "    Chroma,\n",
    "    # This is the number of examples to produce.\n",
    "    k=1,\n",
    ")\n",
    "\n",
    "# Select the most similar example to the input.\n",
    "question = \"Who was the father of Mary Ball Washington?\"\n",
    "selected_examples = example_selector.select_examples({\"question\": question})\n",
    "print(f\"Examples most similar to the input: {question}\")\n",
    "for example in selected_examples:\n",
    "    print(\"\\n\")\n",
    "    for k, v in example.items():\n",
    "        print(f\"{k}: {v}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b47463b9ea0d7b97",
   "metadata": {},
   "source": [
    "### Feed example selector into FewShotPromptTemplate\n",
    "> Finally, create a FewShotPromptTemplate object. This object takes in the example selector and the formatter for the few-shot examples.<br>\n",
    "> 最后，创建一个 FewShotPromptTemplate 对象。此对象采用示例选择器和少数样本的格式化程序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "81c5a7f36ad537ab",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T10:39:42.458764Z",
     "start_time": "2024-07-17T10:39:35.051022Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Question: Who was the maternal grandfather of George Washington?\n",
      "\n",
      "Are follow up questions needed here: Yes.\n",
      "Follow up: Who was the mother of George Washington?\n",
      "Intermediate answer: The mother of George Washington was Mary Ball Washington.\n",
      "Follow up: Who was the father of Mary Ball Washington?\n",
      "Intermediate answer: The father of Mary Ball Washington was Joseph Ball.\n",
      "So the final answer is: Joseph Ball\n",
      "\n",
      "\n",
      "Question: Who was the father of Mary Ball Washington?\n"
     ]
    }
   ],
   "source": [
    "prompt = FewShotPromptTemplate(\n",
    "    example_selector=example_selector,\n",
    "    example_prompt=example_prompt,\n",
    "    suffix=\"Question: {input}\",\n",
    "    input_variables=[\"input\"],\n",
    ")\n",
    "\n",
    "print(prompt.format(input=\"Who was the father of Mary Ball Washington?\"))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
